package com.bbzn.device.client.service.impl;

import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import com.bbzn.device.client.dataobject.LocusCoordinate;
import com.bbzn.device.client.dao.locus.LocusCoordinateMapper;
import com.bbzn.device.client.service.LocusCoordinateService;
@Service
public class LocusCoordinateServiceImpl implements LocusCoordinateService{

    private static Logger logger = LoggerFactory.getLogger(LocusCoordinateServiceImpl.class);

    //定义一个容量为10000的阻塞队列，BlockingQueue线程安全可以多个生产者同时put
    private BlockingQueue<LocusCoordinate> dataQueue = new LinkedBlockingQueue<LocusCoordinate>(10000);

    private List<LocusCoordinate> list = new ArrayList<LocusCoordinate>();

    @Resource
    private LocusCoordinateMapper locusCoordinateMapper;

    @Override
    public int deleteByPrimaryKey(Long id) {
        return locusCoordinateMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(LocusCoordinate record) {
        return locusCoordinateMapper.insert(record);
    }

    @Override
    public int insertOrUpdate(LocusCoordinate record) {
        return locusCoordinateMapper.insertOrUpdate(record);
    }

    @Override
    public int insertOrUpdateSelective(LocusCoordinate record) {
        return locusCoordinateMapper.insertOrUpdateSelective(record);
    }

    @Override
    public int insertSelective(LocusCoordinate record) {
        return locusCoordinateMapper.insertSelective(record);
    }

    @Override
    public LocusCoordinate selectByPrimaryKey(Long id) {
        return locusCoordinateMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(LocusCoordinate record) {
        return locusCoordinateMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(LocusCoordinate record) {
        return locusCoordinateMapper.updateByPrimaryKey(record);
    }

    @Override
    public List<LocusCoordinate> findByAll(LocusCoordinate locusCoordinate) {
        return locusCoordinateMapper.findByAll(locusCoordinate);
    }

    @Override
    public int deleteByImei(String imei) {
        return locusCoordinateMapper.deleteByImei(imei);
    }

    @Override
    public int updateBatch(List<LocusCoordinate> list) {
        return locusCoordinateMapper.updateBatch(list);
    }

    @Override
    public int updateBatchSelective(List<LocusCoordinate> list) {
        return locusCoordinateMapper.updateBatchSelective(list);
    }

    @Override
    public int batchInsert(List<LocusCoordinate> list) {
        return locusCoordinateMapper.batchInsert(list);
    }

    //put任务的方法，供生产者调用
    @Override
    public void recordJob(LocusCoordinate job) {
        try {
            dataQueue.put(job);
        } catch (InterruptedException e) {
            logger.info("启动批量【GPS轨迹上传】守护线程,批量更新Job入队列异常");
            Thread.currentThread().interrupt();
        }
    }

    @PostConstruct
    @Override
    public void init() {
        Thread thread = new Thread(() -> {
            logger.info("启动批量【GPS轨迹上传】守护线程，启动时间{}", new Date(System.currentTimeMillis()));
            while (Boolean.TRUE) {
                LocusCoordinate poll = null;
                boolean pollTimeOut = false;
                long startTime;
                long endTime;
                try {
                    // poll时设置超时时间为2秒
                    poll = dataQueue.poll(2, TimeUnit.SECONDS);
                } catch (InterruptedException e) {
                    logger.info("启动批量【GPS轨迹上传】守护线程---批量更新Job异常");
                    Thread.currentThread().interrupt();
                }

                if (null != poll) {
                    // poll到任务添加到List中
                    list.add(poll);
                } else {
                    // poll超时，设置超时标志位
                    pollTimeOut = true;
                }

                // 如果任务List等于5000或poll超时且List中还有任务就批量更新
                if (list.size() == 300 ||
                        (pollTimeOut && !CollectionUtils.isEmpty(list))) {
                    startTime = System.currentTimeMillis();
                    batchInsert(list);
                    logger.info("启动批量【GPS轨迹上传】守护线程---Job任务批量更新{}条任务,耗时{}毫秒", list.size(),
                            System.currentTimeMillis() - startTime);
                    list.clear();
                }
            }
        });

        thread.setName("job-batchUpdate-deamon");
        // 设置启动的线程为守护线程 直到jvm停了才停止
        thread.setDaemon(true);
        thread.start();
    }

}
